package com.handinfo.uimenu.window;

import java.io.DataInputStream;
import java.io.IOException;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;

import com.handinfo.engine.AbstractGameScreen;
import com.handinfo.engine.GameMIDlet;
import com.handinfo.engine.GameManager;
import com.handinfo.engine.net.GameProtocol;
import com.handinfo.game.ActorItem;
import com.handinfo.game.ActorRole;
import com.handinfo.uimenu.UIAbstractWindow;
import com.handinfo.uimenu.UIListener;
import com.handinfo.uimenu.UIManager;
import com.handinfo.uimenu.UIMessageBox;
import com.handinfo.uimenu.UITools;
import com.handinfo.uimenu.UIWindowFactory;
import com.handinfo.util.Tools;
import com.test.touch.GameTouchManager;

public class UIAuctionSail extends UIAbstractWindow implements ILBHandler
{

	private final String TITLE = "物品拍卖";
	private final String ALERT = "点击查看";
	// GROUP
	private final int GROUP_ITEM = 1;
	private final int GROUP_COMPETITION = 2;
	private final int GROUP_YIKOUJIA = 3;
	private final int GROUP_LABEL = 4;
	private final int GROUP_BAG = 5;
	// INDEX - SAIL
	private final int INDEX_SAIL_ITEM = 1;
//	private final int INDEX_SAIL_ITEM_COMPETITION = 2;
	private final int INDEX_SAIL_ITEM_YIKOU = 3;
	private final int INDEX_SAIL_LABEL_FIRST = 4;
	private final int INDEX_SAIL_BAG_FIRST = INDEX_SAIL_LABEL_FIRST + ActorItemLBHandler.NUM_LABEL_DIS;
	//
//	private String ATT_MONEY_COMPETION = "竞价 :";
	private String ATT_MONEY_YIKOU = "一口价 :";
	private String ATT_MONEY_BAOGUAN = "保管费 :";
	private String ATT_SAIL = "竞拍品 :";
	// Var
	private ActorItem m_item_sail;// 要卖的道具
	private ActorItem[] m_items_bag_copy;// 背包道具 - 临时
	private long m_money_yikou;
	private long m_money_auction;
	private int m_scale;
	//
	private ActorItemLBHandler m_bag_handler;//背包处理器

	public UIAuctionSail(int id)
	{
		super(id);
		//
		setBounds(UITools.X_BG, UITools.Y_BG, UITools.W_BG, UITools.H_BG);
	}

	public void createNotify()
	{
		// 初始化状态及索引
		m_items_bag_copy = getCopyActorItems();
		m_bag_handler = new ActorItemLBHandler(this);
		m_bag_handler.setLabelByLabelId(ActorItem.TYPE_GOODS_ALL);
		this.setWindowIndex(INDEX_SAIL_BAG_FIRST);
	}

	protected int countGroupId(int mIndex)
	{
		if (mIndex < INDEX_SAIL_ITEM_YIKOU) {
			return GROUP_ITEM;
		}
		else if (mIndex < INDEX_SAIL_ITEM_YIKOU) {
			return GROUP_COMPETITION;
		}
		else if (mIndex < INDEX_SAIL_LABEL_FIRST) {
			return GROUP_YIKOUJIA;
		}
		else if (mIndex < INDEX_SAIL_BAG_FIRST) {
			return GROUP_LABEL;
		}
		else {
			return GROUP_BAG;
		}
	}

	protected int countGroupIndex(int mGroupId, int mIndex)
	{
		switch (mGroupId) {
			case GROUP_LABEL:
				return mIndex - INDEX_SAIL_LABEL_FIRST;
			case GROUP_BAG:
				return mIndex - INDEX_SAIL_BAG_FIRST;
			default:
				return 0;
		}
	}

	protected void actionOnIndexChanged()
	{
		m_bag_handler.updateOnStateOrIndexChanged();
	}

	private ActorItem[] getCopyActorItems()
	{
		ActorItem[] items = new ActorItem[ActorRole.NUM_BAG_GOODS];
		ActorItem[] items_bag = GameManager.getInstance().m_role.m_bag_goods;
		for (int i = 0; i < items.length; i++) {
			items[i] = items_bag[i];
		}
		return items;
	}

	// ////////////////////////
	// IBagHandler
	// ////////////////////////
	public Object[] getBagDatas()
	{
		return m_items_bag_copy;
	}

	public int getUpIndex()
	{
		switch (this.m_groupId) {
			case GROUP_LABEL:
				return INDEX_SAIL_ITEM_YIKOU;
			case GROUP_BAG:
			default:
				return m_bag_handler.getCurrentLabelWindowIndex();
		}
	}

	public int getDownIndex()
	{
		switch (this.m_groupId) {
			case GROUP_LABEL:
				return INDEX_SAIL_BAG_FIRST;
			case GROUP_BAG:
				return INDEX_SAIL_ITEM;
			default:
				Tools.debugPrintln("无此组Id = " + this.m_groupId);
				return 1;
		}
	}

	public int getLeftIndex()
	{
		switch (this.m_groupId) {
			case GROUP_LABEL:
				return INDEX_SAIL_ITEM_YIKOU;
			case GROUP_BAG:
			default:
				return INDEX_SAIL_LABEL_FIRST + ActorItemLBHandler.NUM_LABEL_DIS - 1;
		}
	}

	public int getRightIndex()
	{
		switch (this.m_groupId) {
			case GROUP_LABEL:
				return INDEX_SAIL_ITEM_YIKOU;
			case GROUP_BAG:
			default:
				return INDEX_SAIL_ITEM;
		}
	}

	public int getFirstIndex(int idComp)
	{
		switch (idComp) {
			case AbsLBHandler.TYPE_BAG:
				return INDEX_SAIL_BAG_FIRST;
			case AbsLBHandler.TYPE_LABEL:
			default:
				return INDEX_SAIL_LABEL_FIRST;
		}
	}

	public int getGroupIndex()
	{
		return this.m_groupIndex;
	}

	public int getWindowIndex()
	{
		return this.m_index;
	}

	// ////////////////////////
	// keyLogic
	// ////////////////////////

	public static void recvMessage(int orderId, DataInputStream dis) throws IOException
	{
		UIAuctionSail sail = (UIAuctionSail) UIManager.getInstance().getWindowById(UIWindowFactory.WINDOW_AUCTION_SAIL);
		switch (orderId) {
			case GameProtocol.CS_AUCTION_OPEN_SAIL:
				if (sail == null) {
					sail = (UIAuctionSail) UIManager.getInstance().createWindow(UIWindowFactory.WINDOW_AUCTION_SAIL);
				}
				else {
					return;
				}
				sail.m_scale = dis.readInt();
				break;
			default:
				if (sail != null) {
					sail.recvSail(dis);
				}
				break;
		}
	}

	private void recvSail(DataInputStream dis) throws IOException
	{
		short state = dis.readShort();
		String info = dis.readUTF();
		if (!info.equals("")) {
			GameManager.getInstance().addSystemInfo(GameManager.SYSTEM_INFO_TYPE_B, info);
		}
		if (state == 1) {
			reset();
			//close();
		}
		m_isOperLocked = false;
	}
     
	private void reset(){
		m_item_sail = null;
		m_money_auction = 0;
		m_money_yikou = 0;
		setWindowIndex(INDEX_SAIL_BAG_FIRST);
	}
	boolean m_isOperLocked;

	protected void keyLogic()
	{
		if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
			close();
		}
		if (m_isOperLocked) {
			return;
		}
		if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT)) {
			// 拍卖
			actionLeftSoft();
		}
		else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_KEY0)) {
			ActorItem item = (ActorItem) m_bag_handler.getCurrentBagItem();
			if (item == null) {
				return;
			}
			GameManager.getInstance().m_game_message.sendActorItemDetail(item.m_guid);
		}
		else {
			switch (this.m_groupId) {
				case GROUP_ITEM:
					if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_UP)) {
						this.setWindowIndex(INDEX_SAIL_BAG_FIRST);
					}
					else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_DOWN)) {
						this.setWindowIndex(INDEX_SAIL_ITEM_YIKOU);
					}
					else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
						actionOnItem();
					}
					break;
				case GROUP_COMPETITION:
					if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_UP)) {
						this.setWindowIndex(INDEX_SAIL_ITEM);
					}
					else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_DOWN)) {
						this.setWindowIndex(INDEX_SAIL_ITEM_YIKOU);
					}
					else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
						actionOnMoneyCom();
					}
					break;
				case GROUP_YIKOUJIA:
					if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_UP)) {
						this.setWindowIndex(INDEX_SAIL_ITEM);
					}
					else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_DOWN)) {
						this.setWindowIndex(INDEX_SAIL_LABEL_FIRST);
					}
					else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
						actionOnMoneyYikou();
					}
					break;
				case GROUP_LABEL: {
					int dir = m_bag_handler.keyDir(AbsLBHandler.TYPE_LABEL);
					if (dir == AbsLBHandler.TYPE_DIR_NONE) {
					}
					else if (dir == AbsLBHandler.TYPE_DIR_UNPRO) {
						// 不处理
					}
					else {
						this.setWindowIndex(dir);
					}
				}
					break;
				case GROUP_BAG: {
					int dir = m_bag_handler.keyDir(AbsLBHandler.TYPE_BAG);
					if (dir == AbsLBHandler.TYPE_DIR_NONE) {
						if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
							actionOnBag();
						}
					}
					else if (dir == AbsLBHandler.TYPE_DIR_UNPRO) {
						// 不处理
					}
					else {
						this.setWindowIndex(dir);
					}
				}
					break;
			}
		}
	}

	private void actionLeftSoft()
	{
		if (m_item_sail == null) {
			GameManager.getInstance().addSystemInfo(GameManager.SYSTEM_INFO_TYPE_B, "请输入道具");
		}
//		else if (m_money_auction == 0) {
//			GameManager.getInstance().addSystemInfo(GameManager.SYSTEM_INFO_TYPE_B, "拍价不能为零");
//		}
		else if (m_money_yikou == 0) {
			GameManager.getInstance().addSystemInfo(GameManager.SYSTEM_INFO_TYPE_B, "一口价不能为零");
		}
		else {
			final UIMessageBox messageBox = (UIMessageBox) UIManager.getInstance().createWindow(
					UIWindowFactory.WINDOW_MESSAGEBOX);
			messageBox.setMessage("是否将道具进行拍卖");
			messageBox.setCentre();
			messageBox.addListener(new UIListener() {

				public void actionPerformed()
				{
					if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)
							|| AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT)) {
						m_isOperLocked = true;
						GameManager.getInstance().m_game_message.sendAuctionSail(m_item_sail.m_index,
								m_item_sail.m_num, m_money_auction, m_money_yikou);
						UIManager.getInstance().removeWindow(messageBox);
					}
					else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
						UIManager.getInstance().removeWindow(messageBox);
					}
				}
			});
		}

	}

	private void actionOnItem()
	{
		if (m_item_sail == null) {
			return;
		}
		m_items_bag_copy[m_item_sail.m_index] = m_item_sail;
		m_item_sail = null;
		m_bag_handler.resetBagData();
	}

	private void actionOnMoneyCom()
	{
		gotoMoneyFrom(0, m_money_auction);
	}

	private void actionOnMoneyYikou()
	{
		gotoMoneyFrom(1, m_money_yikou);
	}

	private void actionOnBag()
	{
		ActorItem item = (ActorItem) m_bag_handler.getCurrentBagItem();
		if (item == null) {
			return;
		}
		if (item.m_isOperLocked) {
			GameManager.getInstance().addSystemInfo(GameManager.SYSTEM_INFO_TYPE_B,"该道具已绑定，不能拍卖");
			return ;
		}
		if (m_item_sail != null) {
			m_items_bag_copy[m_item_sail.m_index] = m_item_sail;
		}
		m_item_sail = item;
		m_items_bag_copy[item.m_index] = null;
		if (m_bag_handler.m_id_label != ActorItem.TYPE_GOODS_ALL) {
			m_bag_handler.resetBagData();
		}

		setWindowIndex(INDEX_SAIL_ITEM_YIKOU);
	}

	/**
	 * 进入输入金钱高级界面获得输入金钱
	 * @param now
	 * @return
	 */
	private void gotoMoneyFrom(final int type, long moneyAuction)
	{
		Form myForm = null;
		switch (type) {
			case 0:
				myForm = new Form("输入竞价金额");
				break;

			default:
				myForm = new Form("输入一口价金额");
				break;
		}
		final short[] money = ActorRole.getMoney(moneyAuction);
		final TextField textField1 = new TextField("金：", money[0] == 0 ? "" : String.valueOf(money[0]), 5,
				TextField.NUMERIC);
		final TextField textField2 = new TextField("银：", money[1] == 0 ? "" : String.valueOf(money[1]), 2,
				TextField.NUMERIC);
		final TextField textField3 = new TextField("铜：", money[2] == 0 ? "" : String.valueOf(money[2]), 2,
				TextField.NUMERIC);
		myForm.append(textField1);
		myForm.append(textField2);
		myForm.append(textField3);
		final StringItem info = new StringItem("", "");
		myForm.append(info);

		final Command ok = new Command("确定", Command.OK, 1);
		final Command cancel = new Command("返回", Command.CANCEL, 1);
		myForm.addCommand(ok);
		myForm.addCommand(cancel);
		//
		CommandListener listener = new CommandListener() {

			public void commandAction(Command c, Displayable d)
			{
				if (c == ok) {
					int gold = 0;
					gold = UITools.checkMoney(textField1.getString());
					switch (gold) {
						case -1:
							info.setText("请输入正确数字");
							setMoney(textField1, money[0]);
							return;
						case -2:
							info.setText("金币不能为负数");
							setMoney(textField1, money[0]);
							return;
					}
					//
					int silver = 0;
					silver = UITools.checkMoney(textField2.getString());
					switch (gold) {
						case -1:
							info.setText("请输入正确数字");
							setMoney(textField2, money[1]);
							return;
						case -2:
							info.setText("银币币不能为负数");
							setMoney(textField2, money[1]);
							return;
					}
					//
					int copper = 0;
					copper = UITools.checkMoney(textField3.getString());
					switch (gold) {
						case -1:
							info.setText("请输入正确数字");
							setMoney(textField3, money[2]);
							return;
						case -2:
							info.setText("铜币不能为负数");
							setMoney(textField3, money[2]);
							return;
					}
					short[] temp = new short[3];
					temp[0] = (short) gold;
					temp[1] = (short) silver;
					temp[2] = (short) copper;
					switch (type) {
						case 0:
						m_money_auction = ActorRole.getMoney(temp);
						break;
					default:
						m_money_yikou = ActorRole.getMoney(temp);
						break;
				}
				Display.getDisplay(GameMIDlet.s_instance).setCurrent(GameMIDlet.s_canvas);
			}
			else if (c == cancel) {
				Display.getDisplay(GameMIDlet.s_instance).setCurrent(GameMIDlet.s_canvas);
			}
		}
		};
		myForm.setCommandListener(listener);

		Display.getDisplay(GameMIDlet.s_instance).setCurrent(myForm);
	}

	private void setMoney(TextField textField, short money)
	{
		String temp = money == 0 ? "" : String.valueOf(money);
		textField.setString(temp);
	}

	// ////////////////////////
	// paintContent
	// ////////////////////////

//	private String[] des = Tools.getStrArray("选择道具输入一口价"+ Tools.CHANGE_ROW + "拍卖成功将收取5%手续费", UITools.W_CONTENT) ;
	private String[] des = Tools.getStrArray("选择道具输入一口价", UITools.W_CONTENT);

	protected void paintContent(Graphics g)
	{
		UITools.paintBackGround(g, m_x, m_y, m_w, m_h, TITLE, ALERT, true, true);
		int tempY = m_y + UITools.INITY_CONTENT;
		m_bag_handler.setInitXY(tempY);
		m_bag_handler.paintLabel(g);
		m_bag_handler.paintBag(g);
		m_bag_handler.paintDrag(g);
		m_bag_handler.paintBagFocused(g);
		//
		int tempX = m_x + UITools.INITX_CONTENT;
		tempY += m_bag_handler.getLBHeight() + UITools.IH_RECTS;
		paintSailItem(g, tempX, tempY);
		tempY += (UIManager.IMAGE_ITEM_OPEN.getHeight() + UITools.IH_RECTS);
//		paintMoneyCompetion(g, tempX, tempY);
//		tempY += (UITools.H_MONEY_GAME + 10);
		paintMoneyYikou(g, tempX, tempY);
		tempY += AbstractGameScreen.FONT_H;
		paintMoneyBaoguan(g, tempX, tempY);
		tempY += AbstractGameScreen.FONT_H + UITools.IH_RECTS;
		m_bag_handler.paintDescribe(g);

		if (des == null) {
			return;
		}
		int tempW = UITools.W_RECT;
		int tempH = UITools.ENDY_CONTENT - tempY + m_y - UITools.IH_RECTS;
		UITools.paintContentRect(g, tempX, tempY, tempW, tempH);
		g.setColor(UIManager.getPaletteColor(UIManager.COLOR_WORD_NOS));
		tempX += UITools.IW_RECT_CONTENT;
		tempY += UITools.IH_RECT_CONTENT;
		for (int i = 0; i < des.length; i++) {
			g.drawString(des[i], tempX, tempY, 0);
			tempY += AbstractGameScreen.FONT_H;
		}
	}

	private void paintSailItem(Graphics g, int x, int y)
	{
		g.setColor(UIManager.getPaletteColor(UIManager.COLOR_WORD_NOS));
		String temp = ATT_SAIL;
		g.drawString(temp, x, y, 0);
		x += AbstractGameScreen.s_font.stringWidth(temp);
		x += 10;
		UITools.paintActorItem(g, x, y, m_item_sail, false, this.m_groupId == GROUP_ITEM, true);
		if (m_item_sail != null) {
			g.setColor(UIManager.getPaletteColor(UIManager.COLOR_WORD_NOS));
			g.drawString(m_item_sail.m_name, x + UIManager.IMAGE_ITEM_CLOSE.getWidth() + UITools.IW_RECT_CONTENT, y, 0);
		}
	}

	private void paintMoneyYikou(Graphics g, int x, int y)
	{
		paintMoneyAuction(g, x, y, GROUP_YIKOUJIA, m_money_yikou, ATT_MONEY_YIKOU, GROUP_YIKOUJIA == this.m_groupId);
	}

	private void paintMoneyBaoguan(Graphics g, int x, int y)
	{
		long money = (m_money_yikou * m_scale) / 1000;
		paintMoneyAuction(g, x, y, GROUP_YIKOUJIA, money <= 0 ? 1 : money, ATT_MONEY_BAOGUAN, false);
	}

	private void paintMoneyAuction(Graphics g, int x, int y, int groupId, long money, String att, boolean isSel)
	{
		g.setColor(UIManager.getPaletteColor(UIManager.COLOR_WORD_NOS));
		g.drawString(att, x, y, 0);
		x += AbstractGameScreen.s_font.stringWidth(att);
		x += 10;
//		UITools.paintMoneyGameRB(g, m_x + m_w - UIManager.getColorsWinBorder().length - 1, y + AbstractGameScreen.FONT_H, money, groupId == this.m_groupId);
		UITools.paintMoneyGameLT(g, x, y, money, isSel);
	}
///////////////////////////////////////////
	private int[][] mlabelRect = null;
	private int[][] mbagRect = null;
	protected void registerTouch() {
		clearAllRects();
		registerNormalSoft();
		int tempY = m_y + UITools.INITY_CONTENT;
		m_bag_handler.setInitXY(tempY);
		int tempX = m_bag_handler.m_x_label;
		tempY = m_bag_handler.m_y_label;
		mlabelRect = new int[m_bag_handler.m_num_label][];
		for (int i = 0; i < m_bag_handler.m_num_label; i++) {
			mlabelRect[i] = new int[]{ tempX, tempY, m_bag_handler.m_w_label, UITools.H_LABEL};
			tempX += (m_bag_handler.m_w_label + m_bag_handler.m_iw_label);
		}
		//////
//		m_bag_handler.paintBag(g);
//		int openDisIndex = ActorRole.s_num_open - m_bag_handler.m_index_data_top;
		tempY = m_bag_handler.m_y_bag;
		mbagRect = new int[m_bag_handler.m_row*m_bag_handler.NUM_BAG_COL][];
		for (int i = 0; i < m_bag_handler.m_row; i++) {
			tempX = m_bag_handler.m_x_bag;
			for (int j = 0; j < m_bag_handler.NUM_BAG_COL; j++) {
				mbagRect[i*m_bag_handler.NUM_BAG_COL+j] = new int[]{tempX, tempY, UITools.W_BAG, UITools.H_BAG};
				tempX += m_bag_handler.RW_BAG;
			}
			tempY += m_bag_handler.RH_BAG;
		}
		int[][]rect = new int[][]{
				{71,153,21,19},	
				{74,177,87,19},	
				{208,277,63,18},
				//
				{333,60,18,26},
				{333,125,18,26},
		};
		
		initTouchRect(mlabelRect);
		initTouchRect(mbagRect);
		initTouchRect(rect);
		
	}

	protected void onTouchRect(int[][] rect, int touchid) {
		if (rect == mlabelRect) {
			if (m_index != touchid+INDEX_SAIL_LABEL_FIRST) {
				setWindowIndex(touchid+INDEX_SAIL_LABEL_FIRST);
			} else {
				GameTouchManager.keyPressedFire();
			}
		} else if (rect == mbagRect) {
			if (m_index != touchid+INDEX_SAIL_BAG_FIRST) {
				setWindowIndex(touchid+INDEX_SAIL_BAG_FIRST);
			} else {
				GameTouchManager.keyPressedFire();
			}
		} else {
			switch(touchid) {
			case 0:
				if (m_index == INDEX_SAIL_ITEM) {
					GameTouchManager.keyPressedFire();
				} else {
					this.setWindowIndex(INDEX_SAIL_ITEM);
				}
			case 1:
				if (m_index == INDEX_SAIL_ITEM_YIKOU) {
					GameTouchManager.keyPressedFire();
				} else {
					this.setWindowIndex(INDEX_SAIL_ITEM_YIKOU);
				}
				break;
			case 2:
				GameTouchManager.keyPressedNum(0);
				break;
			case 3:
				GameTouchManager.keyPressedDir(1);
				break;
			case 4:
				GameTouchManager.keyPressedDir(3);
				break;
			}
		}
	}
	
	
}
